package org.openit.portail.web;

import java.beans.PropertyEditorSupport;

import javax.servlet.http.HttpServletRequest;

import org.openit.portail.dao.ProfilDao;
import org.openit.portail.model.Profil;
import org.openit.portail.model.UserSystem;
import org.openit.portail.service.UserSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(AdminController.URL)
public class AdminController {

	static final String URL = "/admin";
	
	@Autowired
	@Qualifier("userSystemService")
	private UserSystemService userSystemService;
	@Autowired
	private ProfilDao profilDao; 
	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
		binder.registerCustomEditor(Profil.class, "idProfil", new PropertyEditorSupport() {
	        @Override
	        public void setAsText(String text) {
	        	Profil type = profilDao.get(Long.parseLong(text));
	            setValue(type);
	        }
	    });
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String getService(ModelMap model) {
		return "admin";
	}
	@Secured("SUPER_ADMIN,ADMIN")
	@RequestMapping(method = RequestMethod.GET,value="newuser")
	public String getNewFormUser(ModelMap model) {
		
		UserSystem  userSystem=new UserSystem();
		model.addAttribute("usersystem", userSystem);
		return "formuser";
	}
	@Secured("SUPER_ADMIN,ADMIN")
	@RequestMapping(method = RequestMethod.POST,value="newuser")
	public String addNewClient(ModelMap model,@ModelAttribute("usersystem") UserSystem userSystem,BindingResult bindingResult ) {
		if(bindingResult.hasErrors()){
			return "formuser";
		}else{
			try {
				userSystemService.save(userSystem);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "formuser";
			}
			model.put("userlist", userSystemService.findAll());
			return "userlist";
		}
		
	}
	@RequestMapping(method = RequestMethod.GET,value="userlist")
	public String getUserList(ModelMap model) {
		model.put("userlist", userSystemService.findAll());
		return "userlist";
	}
}
